package rmi.drs.util;

import java.util.ArrayList;
import java.util.List;

public class Lock{
	  
	  private boolean isLocked = false;
	  
	  private String item;
	  private String user;
	  
	  private static List<Lock> locks = new ArrayList<Lock>();
	  
	  private Lock(){
		  
	  }
	  
	  private Lock(String item, String user){
		  this.item = item;
		  this.user = user;
		  locks.add(this);
	  }
	  
	  public synchronized void lock()
	  throws InterruptedException{
	    while(isLocked){
	      wait();
	    }
	    isLocked = true;
	  }
	  
	  public synchronized void unlock(){
	    isLocked = false;
	    notify();
	  }

	public boolean isLocked() {
		return isLocked;
	}
	
	
	
	public String getItem() {
		return item;
	}

	public void setItem(String item) {
		this.item = item;
	}

	public String getUser() {
		return user;
	}

	public void setUser(String user) {
		this.user = user;
	}

	public synchronized static Lock getLock(String itemId, String customerId){
		for (Lock l : locks){
			if (l.getItem().equalsIgnoreCase(itemId) && l.getUser().equalsIgnoreCase(customerId)){
				return l;
			}
		}
		return new Lock(itemId, customerId);
	}
	
	public synchronized static Lock getEmotyLock(){
		return new Lock();
	}
}